import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import { visualizer } from 'rollup-plugin-visualizer'
import simpleHtmlPlugin from 'vite-plugin-simple-html'

// 按需自动导入 Element Plus 组件和 API
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig(({ command, mode }) => {
  const isBuild = command === 'build'
  const viteEnv = loadEnv(mode, process.cwd())
  const { VITE_TITLE } = viteEnv

  return {
    plugins: [
      vue(),

      // 自动按需导入 Element Plus 组件
      Components({
        resolvers: [ElementPlusResolver()],
        dts: 'src/components.d.ts', // 生成声明文件，方便 TS
      }),

      // 自动按需导入 Vue 和 Element Plus API（如 ElMessage）
      AutoImport({
        imports: ['vue'],
        resolvers: [ElementPlusResolver()],
        dts: 'src/auto-imports.d.ts',
      }),

      // 打包体积分析
      visualizer({
        open: true,
        gzipSize: true,
        brotliSize: true,
        filename: 'stats.html',
      }),

      // 简单 html 插件，插入 title 等
      simpleHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_TITLE,
          },
        },
      }),
    ],

    base: './',

    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },

    build: {
      chunkSizeWarningLimit: 1024,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('element-plus')) {
                return 'vendor_element-plus'
              }
              if (id.includes('echarts')) {
                return 'vendor_echarts'
              }
              return 'vendor'
            }
          },
        },
      },
    },

    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            'primary-color': '#42b983', // 你项目的主题色
          },
          javascriptEnabled: true,
        },
      },
    },
  }
})
